package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;

public class JoinTournamentCompleteActivity extends BaseActivity implements
View.OnClickListener{
	
	private ProgressDialog progressDialog;
	private Handler myHandler = new Handler();
	
	private String memberid;
	private String round1Answer;
	private int groupnum;
	private String tournamentId;
	
	private List<String> participantList;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_join_tournament_complete);
		
		
		//초기화
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid = pref.getString("memberid", "");
		participantList = new ArrayList<String>();
		
		progressDialog = new ProgressDialog(this);
		
		//전 인텐트 정보 받아오기
		Intent intent = getIntent();
		groupnum = intent.getIntExtra("groupnum", 0);
		tournamentId = intent.getStringExtra("tournamentId");
		round1Answer = intent.getStringExtra("round1Answer");
		
		//클릭 리스너 달기
		((RelativeLayout)findViewById(R.id.btn_ok)).setOnClickListener(this);
		
		//정보 받아오기 및 화면 세팅
		if (isNetworkAvailableAndNotice()) {
			getJoinInfo();
		}
		
	}
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_ok:
				finish();
				Intent intentMoveToPage = new Intent(JoinTournamentCompleteActivity.this,InfoTournamentActivity.class);
				intentMoveToPage.putExtra("tournamentID", tournamentId);
				startActivity(intentMoveToPage);
				break;
			default:
				break;
		}
	}
	
	private void getJoinInfo() {
		progressDialog.setMessage("정보를 불러오고있습니다.");
		progressDialog.show();
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				myHandler.post(new Runnable() {
					@Override
					public void run() {
							try {
								Log.d("tag", "getJoinInfo() start");
								String urlSend = LovetoConstant.JOIN_COMPLETE_TOURNAMENT_URL + "?tournamentId=" + tournamentId + "&groupnum=" + groupnum + "&memberid=" + memberid;
								Log.d("tag", "url : " + urlSend);
								String jsonText = JsonUtils.getStringFromUrl(urlSend);
								Log.d("tag", "jsonText : " + jsonText);
								try {
									JSONArray jsonArray = new JSONArray(jsonText);
									
									for (int i=0;i<jsonArray.length();i++) {
										JSONObject object = jsonArray.getJSONObject(i);
										participantList.add(object.getString("roundparticipant_memberid"));
										Log.d("tag", "participantList add : " + object.getString("roundparticipant_memberid"));
										String url = LovetoConstant.PHOTO_THUMB_URL + object.getString("roundparticipant_memberid") + ".jpg";
										ImageDownloader imageDownloader = new ImageDownloader();
										RelativeLayout layout = null;
										ImageView image = null;
										switch (i) {
										case 0:
											layout = (RelativeLayout)findViewById(R.id.userphoto_01_area);
											image = (ImageView)findViewById(R.id.userphoto_01);
											break;
										case 1:
											layout = (RelativeLayout)findViewById(R.id.userphoto_02_area);
											image = (ImageView)findViewById(R.id.userphoto_02);
											break;
										case 2:
											layout = (RelativeLayout)findViewById(R.id.userphoto_03_area);
											image = (ImageView)findViewById(R.id.userphoto_03);
											break;
										}
										imageDownloader.download(url, image);
										layout.setVisibility(RelativeLayout.VISIBLE);
									}
									
								} catch (JSONException e) {
									e.printStackTrace();
									Log.d("tag", "setRoundInfo() error, " + e.getMessage());
								}
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
								Log.d("tag", "setRoundInfo() error, " + e.getMessage());
							} finally {
								//나머지 정보 세팅
								//본인 사진
								ImageView myImage = (ImageView)findViewById(R.id.photo_mine);
								String url = LovetoConstant.PHOTO_URL + memberid + "_1.jpg";
								ImageDownloader imageDownloader = new ImageDownloader();
								imageDownloader.download(url, myImage);
								//본인 답변 넣기
								((TextView)findViewById(R.id.text_answer)).setText(round1Answer);
								//그룹이름 표시
								setGroupNum(groupnum);
								//참여자 없으면 빈칸 하나 넣어줌
								if (participantList.size() == 0) {
									((RelativeLayout)findViewById(R.id.userphoto_01_area)).setVisibility(RelativeLayout.VISIBLE);
								}
								progressDialog.dismiss();
								Log.d("tag", "getJoinInfo() end");
							}
						}
				});
			}
		};
		new Thread(runnable).start();
	}
	
	private void setGroupNum(int groupnum) {
		
		ImageView v_group = (ImageView) findViewById(R.id.img_group_alphabet);
		switch (groupnum) {
		case 1:
			v_group.setImageResource(R.drawable.text_info_tournament_group_01);
			break;
		case 2:
			v_group.setImageResource(R.drawable.text_info_tournament_group_02);
			break;
		case 3:
			v_group.setImageResource(R.drawable.text_info_tournament_group_03);
			break;
		case 4:
			v_group.setImageResource(R.drawable.text_info_tournament_group_04);
			break;
		case 5:
			v_group.setImageResource(R.drawable.text_info_tournament_group_05);
			break;
		case 6:
			v_group.setImageResource(R.drawable.text_info_tournament_group_06);
			break;
		case 7:
			v_group.setImageResource(R.drawable.text_info_tournament_group_07);
			break;
		case 8:
			v_group.setImageResource(R.drawable.text_info_tournament_group_08);
			break;
		}
		
	}
	
}
